import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({ providedIn: 'root' })

export class ExportFileService {

  constructor(private http: HttpClient) { }

  getDown(url, name) {
    this.http.get(url, { responseType: 'blob' }).subscribe((res: any) => {
      this.response(res, name);
    });
  }
  postDown(url, param, name) {
    this.http.post(url, param, { responseType: 'blob' }).subscribe((res: any) => {
      this.response(res, name);
    });
  }
  response(res, name) {
    if (res instanceof Blob) {
      const link: HTMLAnchorElement = document.createElement('a');
      link.style.display = 'none';
      link.href = URL.createObjectURL(res);
      link.setAttribute('download', name);
      document.documentElement.appendChild(link);
      link.click();
      document.documentElement.removeChild(link);
    }
  }
  tableExport(table, name) {
    const uri = 'data:application/vnd.ms-excel;base64,';
    const template = `
    <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>
        <body><table>{table}</table></body>
    </html>`;
    if (!table.nodeType) table = document.getElementById(table);
    const ctx = {
      worksheet: 'Worksheet',
      table: table.innerHTML
    };
    const link = document.createElement("a");
    link.style.display = 'none';
    link.href = uri + this.tableBase64(this.tableFormat(template, ctx));
    link.setAttribute('download', name);
    document.documentElement.appendChild(link);
    link.click();
    document.documentElement.removeChild(link);
  }
  tableBase64(s) {
    return window.btoa(unescape(encodeURIComponent(s)));
  }
  tableFormat(s, c) {
    return s.replace(/{(\w+)}/g, (m, p) => {
      return c[p];
    });
  }
}
